/* eslint-disable indent */
'use strict'

const Controller = require('egg').Controller
const dayjs = require('dayjs')
const { encrypt, decrypt } = require('../extend/cryptoData')

/**
 * @controller Place 门店模块
 */

class PlaceController extends Controller {

    /**
   * @summary 分页查询门店列表
   * @description 分页查询门店列表
   * @router post /v1/place/list
   * @request body PlaceList 分页参数
   * @response 0 PlaceInfo
   */
    async list() {
        const { service, helper, request } = this.ctx
        const params = request.body

        const data = await service.place.getPlaceList(params)
        if (data) {
            helper.success(data)
        }
    }

    /**
       * @summary 新建门店
       * @description 只有登录后才有权限
       * @router post /v1/place/create
       * @request body PlaceCreate 门店参数
       * @response 0 PlaceInfo
       */
    async create() {
        const { service, helper, request, validate, rule } = this.ctx
        const params = request.body

        // 参数校验
        const passed = await validate.call(this, rule.PlaceCreate, request.body)
        if (!passed) {
            helper.error(null, '参数错误')
            return
        }
        const data = await service.place.createPlace(params)
        if (data) {
            helper.success(data)
        }
    }

    /**
       * @summary 编辑门店
       * @description 只有登录后才有权限
       * @router post /v1/place/edit
       * @request body PlaceEdit 参数
       * @response 0 PlaceInfo
       */
    async edit() {
        const { service, helper, request, validate, rule } = this.ctx
        const params = request.body

        // 参数校验
        const passed = await validate.call(this, rule.PlaceEdit, request.body)
        if (!passed) {
            helper.error(null, '参数错误')
            return
        }
        const data = await service.place.editPlace(params)
        if (data) {
            helper.success(data)
        }
    }

    /**
       * @summary 删除门店
       * @description 只有登录后才有权限
       * @router post /v1/place/delete
       * @request body PlaceDelete 参数
       * @response 0 PlaceInfo
       */
    async delete() {
        const { service, helper, request, validate, rule } = this.ctx
        const params = request.body

        // 参数校验
        const passed = await validate.call(this, rule.PlaceDelete, request.body)
        if (!passed) {
            helper.error(null, '参数错误')
            return
        }
        const data = await service.place.deletePlace(params)
        if (data) {
            helper.success(data)
        }
    }

    // 门店授权
    async auth() {
        const { service, helper, request, validate, rule, logger } = this.ctx
        const params = request.body
        console.log('授权', params.data)

        // 转发
        try {
            const url = 'http://api.44944.xyz/v3/store/auth'
            this.ctx.curl(url, {
                method: 'POST',
                data: params,
                dataType: 'json',
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(res => {
                console.log('转发成功: ', res.data)
                logger.info(`转发成功: ${JSON.stringify(res.data)}`)
            }).catch(err => {
                console.log('转发失败: ', err)
                logger.error(`转发失败: ${err}`)
            })
        } catch (error) {
            console.log('转发错误: ', error)
            logger.error(`转发错误: ${error}`)
        }


        // 控制数据是否加密
        const isEncrypt = this.app.config.aes.isencrypt

        if (isEncrypt) {
            // 加密数据
            // 参数校验
            if (!params?.data) {
                helper.failed(null, '参数错误')
                return
            }

            // 解密数据
            try {
                const decryptData = decrypt(params.data, this.app.config.aes.key, this.app.config.aes.iv)
                if (!decryptData) {
                    helper.failed(1002, null, '数据错误')
                    return
                }
                const decryptJson = JSON.parse(decryptData)
                // 校验时间戳
                if (dayjs(decryptJson.timestamp).isAfter(dayjs().subtract(2, 'minutes'))) {
                    helper.failed(1002, null, '数据时间错误')
                    return
                }
                if (!decryptJson.nonce || !decryptJson.barcode) {
                    helper.failed(1002, null, '数据格式错误')
                    return
                }

                const data = await service.place.authPlace(decryptJson)
                if (data) {
                    // 判断有效期
                    if (dayjs(data.expires).isAfter(dayjs())) {
                        const response = {
                            barcode: data.barcode,
                            barname: data.barname,
                            expires: data.expires,
                            appid: '21142',
                            timestamp: dayjs().unix()
                        }
                        console.log('response', response)
                        const strData = encrypt(JSON.stringify(response), data.barcode, decryptJson.nonce)
                        helper.success({
                            token: strData
                        })
                    } else {
                        helper.failed(2001, null, '授权已过期')
                    }
                }
            } catch (error) {
                helper.failed(1002, null, '数据错误')
            }

        } else {
            // 不加密
            // 参数校验
            const passed = await validate.call(this, rule.PlaceAuth, request.body)
            if (!passed) {
                helper.error(null, '参数错误')
                return
            }

            const data = await service.place.authPlace(params)
            if (data) {
                // 判断有效期
                if (dayjs(data.expires).isAfter(dayjs())) {
                    helper.success(data)
                } else {
                    helper.failed(2001, null, '授权已过期')
                }
            }
        }
    }

    // 通过barcode查询门店信息
    async getPlaceByBarCode() {
        const { service, helper, request, validate, rule } = this.ctx
        const params = request.body

        // 参数校验
        if (!params.barcode) {
            helper.error(null, '参数错误')
            return
        }
        const data = await service.place.getPlaceByBarcode(params)
        if (data) {
            helper.success(data)
        }
    }

    // 更新门店SDK版本号
    async updatePlaceSdkVersion() {
        const { service, helper, request, validate, rule } = this.ctx
        const params = request.body

        // 参数校验
        const passed = await validate.call(this, rule.PlaceEditVersion, request.body)
        if (!passed) {
            helper.error(null, '参数错误')
            return
        }
        const data = await service.place.editPlaceVersion(params)
        if (data) {
            helper.success(data)
        }
    }
}


module.exports = PlaceController
